const request = require('request')
const { API_CONFIG } = require('../../../config')

const replaceWords = ['来张', '来一张'] // 无效描述词
export function handleNormalChat ({bot, msg, currentEnv, currentContact, content, botNickName}) {
  currentEnv.instance.addMessage(currentContact.NickName, content)
  if (content.includes(botNickName)) {
    // 消息中包含二狗也回复
    const pattern = /(.*)(图|照)片/
    if (pattern.test(content)) {
      currentEnv.instance.popMessage()
      let imgContent = pattern.exec(content)[1].replace(botNickName, '')
      for (let i = 0; i < replaceWords.length; i++) {
        imgContent = imgContent.replace(replaceWords[i], '')
      }
      bot
        .request({
          method: 'GET',
          url: 'https://image.baidu.com/search/acjson',
          params: {
            tn: 'resultjson_com',
            word: imgContent,
            queryWord: imgContent
          }
        })
        .then(res => {
          const imgArr = res.data.data
          if (!imgArr) return
          const canUseImgArr = []
          imgArr.forEach(item => {
            if (item.replaceUrl) {
              const imgUrl = item.replaceUrl[0].ObjURL
              if (/\.jpe?g$/.test(imgUrl)) {
                canUseImgArr.push(imgUrl)
              }
            }
          })
          if (!canUseImgArr.length) {
            bot.sendMsg('该关键词下无图可看', msg.FromUserName)
            return
          }
          const index = Math.floor(Math.random() * canUseImgArr.length)
          const imgUrl = canUseImgArr[index]
          bot.sendMsg({
            file: request(imgUrl),
            filename: 'preview.jpg'
          }, msg.FromUserName)
            .catch(err => {
              bot.sendMsg('该关键词下图片异常，建议切换关键词重试', msg.FromUserName)
              bot.emit('error', err)
            })
        })
      return
    }
    bot
      .gptRequest({
        method: 'POST',
        url: API_CONFIG.chatUrl,
        data: { messages: currentEnv.instance.getMessage() }
      })
      .then(res => {
        currentEnv.instance.addMessage(botNickName, res.data)
        bot.sendMsg(res.data, msg.FromUserName)
      })
  }
}
